var map;
var curCenterLat = '52.0862573323384';
var curCenterLng = '4.89990234375';
var app;
var itemId;
var newMarker;

var options = { 
	clickable: true,
	draggable: false
};

function load() 
{
	if (GBrowserIsCompatible()) 
	{
		map = new GMap2(document.getElementById("map"));
		map.disableDoubleClickZoom();
		map.enableScrollWheelZoom();
		map.addControl(new GLargeMapControl());
		map.addControl(new GMapTypeControl());
		map.setCenter(new GLatLng(52.0862573323384, 4.89990234375), 7);
	  	
	  	
		GEvent.addListener(map, "dblclick",
			function (overlay, latlng)
			{
				if (latlng) 
				{
					addNewPoint(latlng.lat(), latlng.lng());
				}
			}
		);

		GEvent.addListener(map, "dragend", 
	    	function()
			{
		    	var gp = map.getCenter();
		    	if (gp)
		    	{
		    		curCenterLat = gp.lat().toString();
		    		curCenterLng = gp.lng().toString();
		    	}
			}
		);
		app = document.getElementById( 'lzapp' );
	}
}

function getCurrentCenter()
{
	return curCenterLat + ';' + curCenterLng;
}

function addPoint(itemId, lat, lng, locationId, description, rating)
{
	
	var marker = new GMarker(new GLatLng(lat,lng, true), options);
	var fullDescr = description;
	fullDescr += '<p>Waardering: '+rating+'</p>';
	fullDescr += '<p><a href="javascript:vote('+locationId+',1);"><image src="/web/resources/thumbs_up.png" width="30" height="28" border="0"></a>&nbsp;<a href="javascript:vote('+locationId+',-1);"><image src="/web/resources/thumbs_down.png" width="30" height="25" border="0"></a></p>';
	marker.bindInfoWindowHtml(fullDescr);
	if (map)
		map.addOverlay(marker);
}

function addNewPoint(lat, lng)
{
	//if (itemId)
	//{
		if (newMarker)
		{
			map.removeOverlay(newMarker);
		}
		newMarker = new GMarker(new GLatLng(lat,lng, true), options);
		var submitContent = '<form action="#" onsubmit="javascript:sendNewPoint('+itemId+', this.descr.value, '+lat+', '+lng+');">';
		submitContent += 'Voeg hier een beschrijving toe:<br><textarea rows="5" cols="20" name="descr"></textarea><input type="submit" value="Voeg toe"></form>'
		newMarker.bindInfoWindowHtml(submitContent);
		if (map)
		{
			map.addOverlay(newMarker);
			newMarker.openInfoWindowHtml(submitContent);
		}
		
//		GEvent.addListener(newMarker, "infowindowclose",
//			function()
//			{
//				map.removeOverlay(newMarker);
//			}
//		);
//	}
//	else {
//		
//	}
}

// Call functions towards SWF
function vote(locationId, rating)
{
	if (app)
		app.voteForLocation(locationId,rating);
}

function sendNewPoint(item, description, lat, lng)
{
	if (app)
		app.addNewPoint(item, description, lat, lng);
		
	newMarker = null;
}